
"""访问限制"""

"""
1: 超级管理员
2: 管理员
3: 只读用户
"""
# 配置:
    # 在对应的列表中加入请求url，并在需要限制权限的views函数中加入判断以下即可：
"""
    if access_rt(request,models) == permission_status:#判断是否有权限访问函数
        return HttpResponse(permission_status)
    else:
"""
import os
import json
from configCT.settings import logger
from configCT.settings import BASE_DIR
from django.shortcuts import render

def access_rt(request,models):
    role_permissions_file = os.path.join(BASE_DIR, "configCT", "role_permissions_file.json")
    with open(role_permissions_file, "r", encoding="utf-8") as f:
        role_permissions_dict = json.loads(f.read())
    request_url = request.path
    if "-" in request_url:
        request_url = request_url.split("-")[0] + "/"

    if request_url == "/super_cmdb/login/" or request_url == "/super_cmdb/index/" or "api" in request_url:
        return True
    user_id = request.session.get("user_id")
    if user_id:
        usertype_id = models.User.objects.filter(id=user_id).first().usertype_id
        #print("===================usertype_id:", usertype_id,request_url)
        if "%s"%usertype_id in role_permissions_dict.keys():    #key为字符串
            if request_url not in role_permissions_dict["%s"%usertype_id]:
                logger.info("你没有此页面的访问权限，请退出")
                return False
            else:
                return True
        else:
            logger.info("角色没有授权，请联系管理员。")
            return False
    else:
        logger.info("还没有登陆，跳转到登陆页面")
        return render(request,"super_cmdb/login.html")
